<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\Db; // 数据库的链接
use app\Sms;
use RangeException;
use think\facade\Cache;
class User extends BaseController
{
    // 注册
    public function register()
    {
        $post = input();
        // 验证是否正确手机号
        if (!preg_match("/^1[34578]\d{9}$/", $post['phone'])) {
            return json(['code' => 500,'msg' => '手机号格式不正确']);
        }

        // 验证是否重复手机号
        $user = Db::name('user')->where('phone', $post['phone'])->find();
        if ($user) {
            return json(['code' => 500,'msg' => '手机号已注册']);
        }

        // 验证密码是否正确
        if (strlen($post['password']) < 6) {
            return json(['code' => 500,'msg' => '密码长度不能小于6位']);
        }

        // 验证验证码是否正确
        $code = Cache::store('redis')->get('code_'.$post['phone']);
        if ($code!= $post['code']) {
            return json(['code' => 500,'msg' => '验证码错误']);
        }

        // 如果用户填写sid 就查询是否存在
        if (!empty(@$post['sid'])) {
            $sid = Db::name('user')->where('id', $post['sid'])->find();
            if ($sid) {
                return json(['code' => 500,'msg' => '该邀请人不存在']);
            }
        }

        // 保存用户信息到数据库
        $data = [
            'phone' => $post['phone'],
            'pass' => md5($post['password']),
            'sid' => @$post['sid'],
            'register_time' => time(),
        ];

        // 保存用户信息
        $res = Db::name('user')->insertGetId($data);
        if ($res) {
            return json(['code' => 200,'msg' => '注册成功','data' => array('token' => createToken($res))]);
        } else {
            return json(['code' => 500,'msg' => '注册失败']);
        }
    }

    

    // 获取验证码
    public function getCode()
    {
        $post = input();

        // 验证是否正确手机号
        if (!preg_match("/^1[34578]\d{9}$/", $post['phone'])) {
            return json(['code' => 500,'msg' => '手机号格式不正确']);
        }

        // 获取缓存中的验证码
        $rediscode = Cache::store('redis')->get('code_'. $post['phone']);
        if ($rediscode) {
            return json(['code' => 500,'msg' => '请勿重复获取验证码']);
        }

        // 生成验证码
        $code = rand(1000, 9999);

        // 保存验证码到缓存
        Cache::store('redis')->set('code_'.$post['phone'],$code,310);

        // 发送短信验证码
        $Sms = new Sms;
        $result = $Sms->send($post['phone'],"【足球联盟】您的验证码是:" .$code."。请不要把验证码泄露给其他人,验证码有效期为5分钟。");

        // json转数组

        $result = json_decode($result,true);

        if($result['msg'] == 'success'){
            return json(['code' => 200,'msg' => '获取短信成功!']);
        }else{
            return json(['code' => 500,'msg' => '获取短信失败!']);
        }
    }
    // 登录
    public function login()
    {
        $post = input();

        // 验证是否正确手机号
        if (!preg_match("/^1[34578]\d{9}$/", $post['phone'])) {
            return json(['code' => 500,'msg' => '手机号格式不正确']);
        }

        // 验证密码是否正确
        if (strlen($post['password']) < 6) {
            return json(['code' => 500,'msg' => '密码长度不能小于6位']);
        }

        // 验证用户是否存在
        $user = Db::name('user')->where('phone', $post['phone'])->find();
        if (!$user) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }

        // 验证密码是否正确
        if ($user['pass']!= md5($post['password'])) {
            return json(['code' => 500,'msg' => '密码错误']);
        }
        $user['pass'] = '';
        // 登录成功
        return json(['code' => 200,'msg' => '登录成功','data' => array('token' => createToken($user['id']),'userinfo' => $user)]);
    }
    // 获取用户信息 不包含密码 
    public function getUserInfo()
    {
        $UID = request()->UID;
        $user = Db::name('user')->where('id', $UID)->field('*')->find();

        // 查是否为商会成员
        $user['is_agent'] = 0;
        $agent = Db::name('agent')->where('uid', $UID)->where('is_status', 0)->find();
        if ($agent) {
            $user['is_agent'] = 1;
        }

        if (!$user) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }
        return json(['code' => 200,'msg' => '获取成功','data' => $user]);
    }
    // 通过验证码修改密码
    public function changePassword()
    {
        $post = input();


        // 验证是否正确手机号
        if (!preg_match("/^1[34578]\d{9}$/", $post['phone'])) {
            return json(['code' => 500,'msg' => '手机号格式不正确']);
        }

        // 验证是否重复手机号
        $user = Db::name('user')->where('phone', $post['phone'])->find();
        if (!$user) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }

        // 验证验证码是否正确
        $code = Cache::store('redis')->get('code_'. $post['phone']);
        if ($code!= $post['code']) {
            return json(['code' => 500,'msg' => '验证码错误']);
        }

        // 修改密码
        $res = Db::name('user')->where('id', $user['id'])->update(['pass' => md5($post['password'])]);
        if ($res) {
            return json(['code' => 200,'msg' => '修改密码成功']);
        } else {
            return json(['code' => 500,'msg' => '修改密码失败']);
        }
    }
    // 银牌兑换金牌
    public function exchange()
    {
        $post = input();
        $UID = request()->UID;
        $user = Db::name('user')->where('id', $UID)->find();
        // 判断用户是否存在
        if (!$user) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }
       
        $set = getSetting('config'); // 获取设置信息
        $gold_exchange = $set['gold']; // 获取金牌兑换银牌的比例


        if($post['sum'] <= 0){
            return json(['code' => 500,'msg' => '数量错误!']);
        }

        // 判断是否有足够的银牌
        if ($user['silver'] < $post['sum'] * $gold_exchange) {
            return json(['code' => 500,'msg' => '银牌不足']);
        }

        // 开启事务
        Db::startTrans();
        try {
            // 扣除银牌
            $res1 = userRecord($UID, $post['sum'] * $gold_exchange, 0,1,'银牌兑换金牌'.$gold_exchange.":".$post['sum']);
            // 增加金牌
            $res2 = userRecord($UID, $post['sum'],1,0,'金牌兑换银牌'.$gold_exchange.":".$post['sum']);

            if (!$res1 || !$res2) {
                return json(['code' => 500,'msg' => '兑换失败']);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 200,'msg' => '兑换成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500,'msg' => '兑换失败']);
        }
    }
    // 金牌赠送给指定用户
    public function give()
    {
        $post = input();
        $UID = request()->UID;
        $set = getSetting('config'); // 获取设置信息
        $Service = $set['service']; // 转账配置信息
        $Top = $set['top'];
        $remarks = $post['remark'];
        // 不能赠送给自己
        if ($post['sid'] == $UID) {
            return json(['code' => 500,'msg' => '不能赠送给自己']);
        }
        
        // 3个起转

        if ($post['sum'] < $Service['min']) {
            return json(['code' => 500,'msg' => '转账金牌最少3个起']);
        }

        // 正则验证是否为整数

        if (!preg_match("/^[1-9]\d*$/", $post['sum'])) {
            return json(['code' => 500,'msg' => '请输入整数']);
        }

        $user = Db::name('user')->where('id', $UID)->find();
        $suser = Db::name('user')->where('id', $post['sid'])->find();// 获取被赠送用户



        // 判断用户是否存在
        if (!$suser) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }

        // 顶商 和 一级代理没有手续费
        // --- 查询一下 agent uid = uid 和 is_status = 0
        $agent = Db::name('agent')->where('uid', $user['id'])->where('is_status', 0)->find();

        if($user['is_president'] == 1 || !empty($agent)){
            // 转账人 是 顶商和代理没有手续费
            $user_service = 0;
        }else{
            // 手续费 
            $user_service = $this->getRecord($UID,$post['sum'],$Service);
        }

        $zeng = 0;
        // 收款人是顶商 或 1级代理 要额外增加收益
        $agents = Db::name('agent')->where('uid', $suser['id'])->where('is_status', 0)->find();
        if($suser['is_president'] == 1 || !empty($agent)){
            
            if($suser['is_president'] == 1){
                // 收款人是顶商
                // 要增加收款金额 保留两位小数
                $zeng = round($post['sum'] * $Top['president_collect'] / 100, 2);
            }else{
                // 收款人是一级代理
                // 保留两位小数
                $zeng = round($post['sum'] * $Top['one_collect'] / 100, 2);
                // 给会长的奖励
                $zeng_top = round($post['sum'] * $Top['noe_president_collect'] / 100, 2);
                userRecord($agents['sid'], $zeng_top,1,0,'顶商会长收益:一级收金牌奖励');
            }
        }

        // 判断是否有足够的金牌
        if ($post['sum'] + $user_service > $user['gold']) {
            return json(['code' => 500,'msg' => '金牌不足']);
        }

        // 开启事务
        Db::startTrans();
        try {
            // 扣除金牌
            $res1 = userRecord($UID, $post['sum'] + $user_service, 1,1,'赠送给ID:'.$post['sid']);
            // 增加金牌
            $res2 = userRecord($post['sid'], $post['sum'] + $zeng,1,0,$remarks.'来自ID:'.$UID);

            if (!$res1 || !$res2) {
                return json(['code' => 500,'msg' => '赠送失败']);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 200,'msg' => '赠送成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500,'msg' => '赠送失败']);
        }
    }

    // 手续费较为复杂独立出来 
    public function getRecord($uid,$sum,$Service)
    {
        // 从手续费低排高
        // 哪么用户购卡的手续费是最低的先查用户的购卡情况
        // 查 当前用户的购卡记录 并且 已使用 未过期
        $card = Db::name('user_card_record')
            ->alias('a')
            ->join('card b','a.cid = b.id')
            ->where('a.uid', $uid)
            ->where('a.is_status', 1)
            ->where('a.del',0)
            ->field('b.service')
            ->order('b.service asc')
            ->find();
        // 如果没有购卡记录 则使用默认的手续费
        if (!$card) {
            // 那就看一下直推实名认证人数 直推满足条件人数
            $count = Db::name('user')->where('sid', $uid)->where('is_auth', 1)->count();
            if ($count >= $Service['pushsum']) {
                return round($sum * $Service['pushsum_service'] / 100, 2);
            }else{
                return round($sum * $Service['default'] / 100, 2);
            }
        } else {
            // 计算 手续费 保留两位小数
            return round($sum * $card['service'] / 100, 2);
        }
    }

    /**
     * 获取背包
     */
    public function getBag()
    {
        $post = input();
        $UID = request()->UID;
        // type 0 碎片 1闪卡
        if(@$post['type'] == 1){
            // 获取用户闪卡 如果cid分组 则按分组显示
            $list = Db::name('user_card_record')
            ->alias('a')
            ->join('card b','a.cid = b.id')
            ->where('a.uid', $UID)
            ->where('a.is_status', 0)
            ->group('a.cid')
            ->field('a.cid,b.image,count(*) as num,b.name')
            ->select()
            ->toArray();
        }else{
             // 查询用户的碎片 通过bid做分组显示数量
            $list = Db::name('ball_debris')
            ->alias('a')
            ->join('ball_type b','a.bid = b.id')
            ->where('a.uid', $UID)
            ->group('a.bid')
            ->where('a.is_status',0)
            ->field('a.bid,b.icon,count(*) as num')
            ->select()
            ->toArray();
        }
        return json(['code' => 200,'msg' => '获取成功','data' => $list]);
    }
    /**
     * 金牌银牌明细 obvious
     */
    public function getobvious()
    {
        $post = input();
        $UID = request()->UID;
        $type = @$post['type']; // 1 金牌 0银牌
        $page = @$post['page']? $post['page'] : 1;
        $limit = @$post['limit']? $post['limit'] : 10;
        $where = [];
        if($type == 1){
            $where[] = ['recharge_type','=',1];
        }else{
            $where[] = ['recharge_type','=',0];
        }
        $where[] = ['uid','=', $UID];
        $list = Db::name('user_record')
        ->field("*,FROM_UNIXTIME(addto_time,'%Y-%m-%d %H:%i:%s') as addto_time")
        ->where($where)
        ->order('id desc')
        ->paginate([
            'list_rows' => $limit,
            'page' => $page
        ])
        ->toArray();
        return json(['code' => 200,'data' => $list,'msg' => '获取成功']);
    }
    /**
     * 获取店长或会长 联系方式
     */
    public function getContact()
    {
        $post = input();
        $type = @$post['type']; // 1 店长 0会长


        if($type == 1){
            // 店长 is_shopowner
            $list = Db::name('user')->where('is_shopowner',1)->field('id,phone,name,shopowner_qq,shopowner_wx')->select()->toArray();
        }else{
            // 会长 is_president
            $list = Db::name('user')->where('is_president',1)->field('id,phone,name,shopowner_qq,shopowner_wx')->select()->toArray();
        }

        return json(['code' => 200,'data' => $list,'msg' => '获取成功']);
    }
    /**
     * 用户信息修改
     */
    public function editUser()
    {
        $post = input();
        $UID = request()->UID;
        // 去掉空
        $data = [];
        foreach ($post as $k => $v) {
            if ($k == 'shopowner_qq' || $k =='shopowner_wx' || $k == 'name' || $k == 'phone' || $k == 'image' || $k == 'president_qq' || $k == 'president_wx' || $k == 'is_auth'  ) {
                $data[$k] = $v;
            }
        }
        

        
        $res = Db::name('user')->where('id', $UID)->update($data);
        if ($res) {
            return json(['code' => 200,'msg' => '修改成功']);
        } else {
            return json(['code' => 500,'msg' => '修改失败']);
        }
    }

    /**
     * 团队信息
     */

    public function getTeam()
    {
        $UID = 1;
        // 今日注册
        // $UID = request()->UID;
        
        // 获取用户信息
        $user = Db::name('user')->where('id', $UID)->field('id,phone,name,sid,register_time')->find();
        if (!$user) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }

        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        

        $user_push = Db::name('user')
            ->where('sid', $UID)
            ->field('id,phone,name,sid,register_time')
            ->select()
            ->toArray();


        // 今日直推
        $day_push = Db::name('user')
            ->where('sid', $UID)
            ->whereBetweenTime('register_time', $todayStart, $todayEnd)
            ->count();
        
        // 累计直推
        $push = Db::name('user')
            ->where('sid', $UID)
            ->count();
        
        // 累计间推
        $team = Db::name('user')
            ->where('sid', $UID)
            ->field('id,phone,name,sid,register_time')
            ->select()
            ->toArray();
        $promotion_total = 0;
        foreach ($team as $k => $v) {
            $promotion_total += Db::name('user')
                ->where('sid', $v['id'])
                ->count();
        }
        
        // $team将二维数组中的id转为字符串用,分割
        $team_ids = $UID;


        // 获取闪卡的类型

        $flash_card = Db::name('card')
            ->where('del',0)
            ->field('id,name')
            ->select()
            ->toArray();

        $tuna = 0;
        $ids = '';
        do{   
            $tuan2 = Db::name('user')
            ->where([['sid','in',$team_ids]])
            ->select()
            ->toArray();
            unset($team_ids);

            // 将tuan2中的id转为字符串用,分割
            foreach ($tuan2 as $k => $v) {
                $ids.= $v['id'].',';
            }

            $team_ids = implode(',', array_column($tuan2, 'id'));
            // 查询闪卡 数量

           
            $tuna += count($tuan2);
        }while(!empty($team_ids));
        
        // 去掉最后一个,
        $ids = rtrim($ids,',');

        // 循环查询闪卡数量
        foreach ($flash_card as $k => $v) {
            // 查询闪卡总数量
            $num = $this->getFlashCard($ids,$v['id']);
            // 查询收益

            $total = $this->getFlashCardTotal($ids,$v['name']);

            $flash_card_num[$k]['num'] = $num['num'];
            $flash_card_num[$k]['total'] = $total;
        }
       
        return json(['code' => 200,'msg' => '获取成功','data' => ['flash_card_num' => $flash_card_num,"userinfo" => $user,'tuna' => $tuna,'day_push' => $day_push,'push' => $push,'promotion' => $promotion_total]]);
    }

    /**
     * 通过id查询用户闪卡数量
     */
    public function getFlashCard($uid,$cid)
    {

        $list = Db::name('user_card_record')
            ->alias('a')
            ->join('card b','a.cid = b.id')
            ->where('a.uid','in', $uid)
            ->where('a.cid', $cid)
            ->where('a.is_status', 1)
            ->where('a.del',0)
            ->field('count(*) as num,b.name')
            ->select()
            ->toArray();
        return $list[0];
    }
    /**
     * 查询 id 对应的闪卡总收益
     * @param $id int 用户id
     * @param $cname string 闪卡名称
     * @return array
     */
    public function getFlashCardTotal($id,$cname)
    {
        $list = Db::name('user_record')
           ->where('uid','in', $id)
           ->where('operation_type',0)
           ->where('remarks','like'.'%'.$cname.'收益%')
           ->sum('amount');
        return $list;
    }
    /**
     * 添加商户成员ID
     */

    public function addMember()
    {
        $post = input();
        $UID = request()->UID;
        $member_id = $post['id'];
        $res = Db::name('user')->where('id', $member_id)->update(['member_id' => $member_id]);
        // 判断用户是否存在
        if (!$res) {
            return json(['code' => 500,'msg' => '用户不存在']);
        }

        // 判断当前用户是否为会长

        $user = Db::name('user')->where('id', $UID)->field('is_president')->find();
        if ($user['is_president'] == 0) {
            return json(['code' => 500,'msg' => '不是会长不能添加成员']);
        }

        // 判断对方是否为会长
        $member = Db::name('user')->where('id', $member_id)->field('is_president')->find();
        if ($member['is_president'] == 1) {
            return json(['code' => 500,'msg' => '对方是会长不能添加']);
        }

        // 判断对方是否为商会成员
        $member = Db::name('agent')->where('uid', $member_id)->where('is_status', 0)->find();
        if (!empty($member)) {
            return json(['code' => 500,'msg' => '对方已是商会成员']);
        }

        // 添加数据
        $data = [
            'uid' => $member_id,
            'sid' => $UID,
            'addt_time' => time(),
        ];

        $res = Db::name('agent')->insert($data);

        if ($res) {
            return json(['code' => 200,'msg' => '添加成功']);
        } else {
            return json(['code' => 500,'msg' => '添加失败']);
        }
    }
    /**
     * 商会成员列表
     */
    public function getMember()
    {

        $post = input();
        
        $list = Db::name('agent')
            ->alias('a')
            ->join('user b','a.uid = b.id')
            ->where('a.sid', $post['id'])
            ->field('a.*,b.phone,b.name,b.register_time,b.president_qq,b.president_wx')
            ->select()
            ->toArray();
        return json(['code' => 200,'msg' => '获取成功','data' => $list]);
    }
}